package com.ed.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.ed.constant.UserConstant;
import com.ed.context.UserContext;
import com.ed.exception.BaseException;
import com.ed.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@CrossOrigin
public class LoginInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
		if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
			System.out.println("Method:OPTIONS");
			return true;
		}
		//从请求中获取 jwt token
		String token = request.getHeader("authorization");
		if (StrUtil.isBlank(token)) {
			throw new BaseException("未登录");
		}
		
		//从 jwt token 中获取登录用户 id
		Integer userId = JwtUtil.parseJwt(token);
		if (userId == null || userId <= 0) {
			throw new BaseException("用户信息有误，请重新登录");
		}
		//保存用户上下文
		UserContext.setCurrentUser(userId);
		log.info("用户id:{},token:{}", UserContext.getCurrentUser(), token);
		return true;
	}
	
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		UserContext.removeCurrentUser();
	}
}
